import {loginByUsername, logout, getUserInfo} from '@/api/login';
import {getToken, setToken, removeToken, setUserInfo, removeUserInfo} from '@/utils/auth';

const user = {
  state: {
    user: {},
    token: getToken(),
    roles: []
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token;
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles;
    },
    /* 设置用户信息 */
    SET_USER: (state, user) => {
      state.user = user;
    }
  },

  actions: {
    // 用户名登录
    LoginByUsername({commit}, userInfo) {
      return new Promise((resolve, reject) => {
        loginByUsername(userInfo).then(response => {
          if (response.code === 20000) {
            commit('SET_TOKEN', response.data.token); // token
            commit('SET_USER', response.data); // userInfo
            setToken(response.data.token);
            setUserInfo(response.data);
            resolve(response);
          } else {
            reject(response);
          }
        }).catch(error => {
          reject(error);
        });
      });
    },
    // 用户名退出登录
    LoginOut({commit}) {
      return new Promise((resolve, reject) => {
        commit('SET_TOKEN', ''); // token
        commit('SET_USER', {}); // userInfo
        setToken('');
        setUserInfo('');
        window.localStorage.setItem('loginChecked', '');
        resolve();
      });
    }
  }
};

export default user;
